import axios from 'axios'
import type { LoginForm, RegisterForm, ApiResponse, LoginResponse, WeChatLoginResponse, WeChatStatusResponse } from '@/types/auth'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:3232/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加 token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token 过期或无效，清除本地存储
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 传统登录
export const login = (data: LoginForm) => {
  return api.post<ApiResponse<LoginResponse>>('/auth/login', data)
}

// 用户注册
export const register = (data: RegisterForm) => {
  return api.post<ApiResponse>('/auth/register', data)
}

// 获取用户信息
export const getProfile = () => {
  return api.get<ApiResponse<{ user: any }>>('/auth/profile')
}

// 验证 Token
export const verifyToken = () => {
  return api.get<ApiResponse>('/auth/verify')
}

// 微信扫码登录
export const wechatLogin = (state?: string) => {
  return api.post<ApiResponse<WeChatLoginResponse>>('/auth/wechat/login', { state })
}

// 检查微信登录状态
export const checkWeChatStatus = (state: string) => {
  return api.get<ApiResponse<WeChatStatusResponse>>(`/auth/wechat/status?state=${state}`)
}

// 获取微信用户信息
export const getWeChatUser = (state: string) => {
  return api.get<ApiResponse<{ user: any }>>(`/auth/wechat/user?state=${state}`)
}

// 微信登出
export const wechatLogout = (state: string) => {
  return api.post<ApiResponse>(`/auth/wechat/logout?state=${state}`)
}

// 导出 api 实例供其他模块使用
export default api
